﻿#ifndef QMLSERIALPORT_H
#define QMLSERIALPORT_H

#include <QObject>
#include <QSerialPortInfo>
// #include <QtQml>
#include <QDebug>
#include <QSerialPort>
#include <unistd.h>

class QmlSerialPort : public QObject
{
    Q_OBJECT
    // QML_ELEMENT
public:
    explicit QmlSerialPort(QObject *parent = nullptr);
    static QmlSerialPort *getInstance();

signals:
    // define signals for Application Service
    void openedSerialPort();
    void closedSerialPort();
    void qmlSerialPort_errorOccurredSignal(QSerialPort::SerialPortError error);
    void logsPrintSignal(QString s);

    void openStateChanged();

    void portNameChanged();

    void parityChanged();

    void baudRateChanged();

    void dataBitChanged();

    void stopBitChanged();

public slots:
    void pushSwitchStatus2QmlSerialPortSlot(int channel, int state);

public:
    // define function for qml
    Q_INVOKABLE QStringList availableList(void);
    Q_INVOKABLE bool open(void);
    Q_INVOKABLE bool close(void);


    bool openState() const;
    void setOpenState(bool newOpenState);

    QString portName() const;
    void setPortName(const QString &newPortName);

    QString parity() const;
    void setParity(const QString &newParity);

    int baudRate() const;
    void setBaudRate(int newBaudRate);

    int dataBit() const;
    void setDataBit(int newDataBit);

    float stopBit() const;
    void setStopBit(float newStopBit);

private:
    bool                     m_openState;
    QString                  m_portName;
    QString                  m_parity;
    int                      m_baudRate;
    int                      m_dataBit;
    float                    m_stopBit;
    Q_PROPERTY(bool openState READ openState WRITE setOpenState NOTIFY openStateChanged FINAL)
    Q_PROPERTY(QString portName READ portName WRITE setPortName NOTIFY portNameChanged FINAL)
    Q_PROPERTY(QString parity READ parity WRITE setParity NOTIFY parityChanged FINAL)
    Q_PROPERTY(int baudRate READ baudRate WRITE setBaudRate NOTIFY baudRateChanged FINAL)
    Q_PROPERTY(int dataBit READ dataBit WRITE setDataBit NOTIFY dataBitChanged FINAL)
    Q_PROPERTY(float stopBit READ stopBit WRITE setStopBit NOTIFY stopBitChanged FINAL)

    QSerialPort              mQSerialPort;

    void log(QString s);

private slots:
    void qSerialPort_errorOccurredSlot(QSerialPort::SerialPortError error);
};

#endif // QMLSERIALPORT_H
